package com.ssm.util.qrcode;

import java.awt.Color;  
import java.awt.Graphics2D;  
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;

import jp.sourceforge.qrcode.QRCodeDecoder;
  
/**
 * 使用QRCode.jar和Qrcode_swetake.jar生成和解析二维码
 * @author Administrator
 *
 */
public class QRCodeUtil {
	
	public static BufferedImage createQRCode(String data) throws Exception{
		Qrcode handler = new Qrcode();
		handler.setQrcodeErrorCorrect('M');
		handler.setQrcodeEncodeMode('B');
		handler.setQrcodeVersion(7);
		BufferedImage bufImg = new BufferedImage(240, 240, BufferedImage.TYPE_INT_RGB);
		Graphics2D gs = bufImg.createGraphics();
		gs.setBackground(Color.WHITE);
		gs.clearRect(0, 0, 250, 250); // 设置图片的大小
		// 设定图像颜色：BLACK
		gs.setColor(Color.BLACK);
		byte[] contentBytes = data.getBytes("UTF-8");
		// 设置偏移量 不设置肯能导致解析出错
		int pixoff = 8;
		// 输出内容：二维码
		final int SIZE = 5;
		if (contentBytes.length > 0 && contentBytes.length < 300) {
			boolean[][] codeOut = handler.calQrcode(contentBytes);
			for (int i = 0; i < codeOut.length; i++) {
				for (int j = 0; j < codeOut.length; j++) {
					if (codeOut[j][i]) {
						gs.fillRect(j * SIZE + pixoff, i * SIZE + pixoff, SIZE, SIZE);
					}
				}
			}
		} else {
			System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. ");
		}
		gs.dispose();
		bufImg.flush();
		return bufImg;
	}
	
	private static String decode(String qrcodePicfilePath) {
		System.out.println("开始解析二维码！！");
		/* 读取二维码图像数据 */
		File imageFile = new File(qrcodePicfilePath);
		BufferedImage image = null;
		try {
		image = ImageIO.read(imageFile);
		} catch (IOException e) {
		System.out.println("读取二维码图片失败： " + e.getMessage());
		return null;
		}
		/* 解二维码 */
		QRCodeDecoder decoder = new QRCodeDecoder();
		String decodedData = new String(decoder.decode(new MyQRCodeImage(image)));
		System.out.println("解析内容如下："+decodedData);
		return decodedData;
		}
	
	
	
	public static void main(String[] args) throws Exception {
//		//生成二维码
//		FileOutputStream out = new FileOutputStream("d:/aaa.png");
//		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//		BufferedImage image = createQRCode("http://www.baidu.com"); //创建图片
//		encoder.encode(image);  //设置jpeg图片编码格式
//		out.close();
		//解析二维码
		String decode = decode("d:/aaa.png");
		System.out.println(decode);
		
	}

}
